package co.gov.medellin.sdep.sisdep.model.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.object.MappingSqlQuery;
import org.springframework.jdbc.object.SqlUpdate;

import co.gov.medellin.sdep.sisdep.model.EstSocioEconomico;
import co.gov.medellin.sdep.sisdep.model.comp.EstSocioEconomicoComp;

public class EstSocioEconomicoDAOImpl extends JdbcDaoSupport implements IEstSocioEconomicoDAO {

    private InsertOperation insertOperation;

    private UpdateOperation updateOperation;

    private DeleteOperation deleteOperation;

    private DeleteByPrimaryKey deleteByPrimaryKey;
    
    private FindByPrimaryKeyQuery findByPrimaryKeyQuery;

    private FindByCriteriaQuery findByCriteriaQuery;

    private FindAllQuery findAllQuery;

    private FindByActiveStateQuery findByActiveStateQuery;

	private static final String SELECT = "SELECT * FROM GES_EST_SOCIO_ECONOMICO_T ";
	private static final String WHERE = " WHERE ";
	private static final String PARAMETER = " ?, ";

    public void delete(EstSocioEconomico estSocioEconomico) {
		deleteOperation.execute( estSocioEconomico  );
	}

	public void deleteByPrimaryKey(long id) {
		deleteByPrimaryKey.execute(id);
	}

	public EstSocioEconomico findByPrimaryKey(long login) {
		return findByPrimaryKeyQuery.runQuery(login);
	}

	public void insert(EstSocioEconomico estSocioEconomico) {
		insertOperation.execute( estSocioEconomico );
	}

	public void update(EstSocioEconomico estSocioEconomico) {
		updateOperation.execute( estSocioEconomico );
	}

	public EstSocioEconomico findByCriteria(EstSocioEconomico  estSocioEconomico) {
		return findByCriteriaQuery.runQuery(estSocioEconomico);
	}

	public List load(EstSocioEconomicoComp  estSocioEconomicoComp) {
		return findAllQuery.runQuery(estSocioEconomicoComp);
	}

	public EstSocioEconomico findByActiveState(EstSocioEconomico  estSocioEconomico) {
		return findByActiveStateQuery.runQuery(estSocioEconomico);
	}

	public void initDao() {
    	insertOperation   = new InsertOperation( getDataSource() );
    	updateOperation = new UpdateOperation(  getDataSource() );
    	findAllQuery = new FindAllQuery( getDataSource() );
    	//Disabled Init
    	//findByPrimaryKeyQuery   = new FindByPrimaryKeyQuery(  getDataSource() );
    	//deleteOperation = new DeleteOperation(  getDataSource() );
    	//deleteByPrimaryKey = new DeleteByPrimaryKey( getDataSource());
    	//findByCriteriaQuery = new FindByCriteriaQuery(  getDataSource() );
    	//findByActiveStateQuery = new FindByActiveStateQuery( getDataSource() );
    }

    // ------------- SaveOperation ---------------------------------------
	class InsertOperation extends SqlUpdate	{
		private static final String sql = "INSERT INTO GES_EST_SOCIO_ECONOMICO_T ("
				  + " ID, "
				  + " CODIGO, "
				  + " FECHA_INGRESO, "
				  + " ID_SOLICITUD, "
				  + " TIPO, "
				  + " ESTADO, "
				  + " USUARIO_CREA, "
				  + " FECHA_CREA "
				  + ") VALUES ("
			  	  + " GES_EST_SOCIO_ECONOMICO_SEC.nextVal, "
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + "SYSDATE"
				  + ")";
		public  InsertOperation(DataSource ds) {
			super(ds,sql);
			//set here required parameters
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.DATE));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			compile();
		}
		public void execute(EstSocioEconomico estSocioEconomico) {
			Long idSequence = new Long(getJdbcTemplate().queryForLong("SELECT GES_EST_SOCIO_ECONOMICO_SEC.nextVal FROM dual"));
			estSocioEconomico.setId(idSequence);
			estSocioEconomico.setCodigo(idSequence.toString());
			InsertOperation.this.update( new Object[]{
				estSocioEconomico.getCodigo(),
				estSocioEconomico.getFechaIngreso(),
				estSocioEconomico.getIdSolicitud(),
				estSocioEconomico.getTipo(),
				estSocioEconomico.getEstado(),
				estSocioEconomico.getUsuarioCrea()
				});
		}
    }

    // ------------- UpdateOperation -------------------------------------
    class UpdateOperation extends SqlUpdate	{
    	private static final String sql = "UPDATE GES_EST_SOCIO_ECONOMICO_T SET "
					  + " CODIGO = ? ,"
					  + " FECHA_INGRESO = ? ,"
					  + " ID_SOLICITUD = ? ,"
					  + " TIPO = ? ,"
					  + " ESTADO = ? ,"
					  + " USUARIO_MODIFICA = ? ,"
					  + " FECHA_MODIFICA = SYSDATE "
				  	  + WHERE
			  	  	  + " ID = ? ";
		public  UpdateOperation(DataSource ds) {
			super(ds,sql);
			//set here required parameters
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.DATE));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.INTEGER));
			compile();
		}
		public void execute(EstSocioEconomico estSocioEconomico) {
			UpdateOperation.this.update( new Object[]{
				estSocioEconomico.getCodigo(),
				estSocioEconomico.getFechaIngreso(),
				estSocioEconomico.getIdSolicitud(),
				estSocioEconomico.getTipo(),
				estSocioEconomico.getEstado(),
				estSocioEconomico.getUsuarioModifica(),
				estSocioEconomico.getId()
				});
		}
    }

    // ------------- DeleteOperation -------------------------------------
    class DeleteOperation extends SqlUpdate	{
		private static final String sql = "DELETE FROM GES_EST_SOCIO_ECONOMICO_T "
										+ WHERE
			  	  	  					+ " CODIGO = ? ";
		public DeleteOperation(DataSource ds) {
			super(ds,sql);
			declareParameter( new SqlParameter(Types.CHAR) );
			compile();
		}
		public void execute(EstSocioEconomico estSocioEconomico) {
			this.update( new Object[]{
				estSocioEconomico.getCodigo(),
			});
		}
	}

    // ------------- DeleteByPrimaryKey ----------------------------------
    class DeleteByPrimaryKey extends SqlUpdate	{
		private static final String sql = "DELETE FROM GES_EST_SOCIO_ECONOMICO_T "
										+ WHERE
			  	  	  					+ " ID = ? ";
		public DeleteByPrimaryKey(DataSource ds) {
			super(ds,sql);
			declareParameter( new SqlParameter(Types.INTEGER) );
			compile();
		}	
		public void execute(long id) {
			this.update( new Object[]{
					new Long(id)
			});
		}	
    }

    // ---- BaseQueryOperation for Mapping ResultSet values --------------
	abstract class BaseQueryOperation extends MappingSqlQuery {
		public BaseQueryOperation(DataSource ds,String sql) {
	   		super(ds,sql);
		}	
		protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
			EstSocioEconomicoComp estSocioEconomico = new EstSocioEconomicoComp();
				estSocioEconomico.setId(new Long(rs.getLong("ID")));
				estSocioEconomico.setCodigo(rs.getString("CODIGO"));
				estSocioEconomico.setFechaIngreso(rs.getDate("FECHA_INGRESO"));		
				estSocioEconomico.setIdSolicitud(new Long(rs.getLong("ID_SOLICITUD")));
				// JOIN TABLA ADM_SOLICITUD_T
				estSocioEconomico.getSolicitud().setRadicado(rs.getString("RADICADO"));
				estSocioEconomico.getSolicitud().setFechaRadicado(rs.getDate("FECHA_RADICADO"));
				estSocioEconomico.setTipo(rs.getString("TIPO"));
				estSocioEconomico.setEstado(rs.getString("ESTADO"));
				estSocioEconomico.setUsuarioCrea(rs.getString("USUARIO_CREA"));
				estSocioEconomico.setFechaCrea(rs.getDate("FECHA_CREA"));		
				estSocioEconomico.setUsuarioModifica(rs.getString("USUARIO_MODIFICA"));
				estSocioEconomico.setFechaModifica(rs.getDate("FECHA_MODIFICA"));		
			return estSocioEconomico;
		}
    }

    // ------------- FindByPrimaryKeyQuery -------------------------------
    class FindByPrimaryKeyQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE
			  	  	  					+ " ID = ? ";
    	public FindByPrimaryKeyQuery(DataSource ds) {
    		super(ds,sql);
			declareParameter( new SqlParameter(Types.INTEGER) );
			compile();
    	}
    	public EstSocioEconomico runQuery(long id) {
			List result =  execute( new Object[]{new Long(id)});
			if ( result.size() > 0 ) {
        		return (EstSocioEconomico) result.get(0);
        	} else {
        		return null;
        	}
    	}
    }

    // ------------- FindByCriteriaQuery ---------------------------------    
    class FindByCriteriaQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE + " 1=1 ";
			//For required criteria elements uncomment required values
			  	  	  					//+ " AND CODIGO = ? "
			  	  	  					//+ " AND FECHA_INGRESO = ? "
			  	  	  					//+ " AND ID_SOLICITUD = ? "
			  	  	  					//+ " AND TIPO = ? "
			  	  	  					//+ " AND ESTADO = ? "
			  	  	  					//+ " AND USUARIO_CREA = ? "
			  	  	  					//+ " AND FECHA_CREA = ? "
			  	  	  					//+ " AND USUARIO_MODIFICA = ? "
			  	  	  					//+ " AND FECHA_MODIFICA = ? "
										//+ "";
    	public FindByCriteriaQuery(DataSource ds) {
    		super(ds,sql);
    		//For required criteria elements uncomment required values
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.DATE) );
			//declareParameter( new SqlParameter(Types.INTEGER) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.DATE) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.DATE) );
			compile();
    	}
    	public EstSocioEconomico runQuery(EstSocioEconomico estSocioEconomico) {
			List result =  execute( new Object[]{
			//For required criteria elements uncomment required values
				//estSocioEconomico.getCodigo(),
				//estSocioEconomico.getFechaIngreso(),
				//estSocioEconomico.getIdSolicitud(),
				//estSocioEconomico.getTipo(),
				//estSocioEconomico.getEstado(),
				//estSocioEconomico.getUsuarioCrea(),
				//estSocioEconomico.getFechaCrea(),
				//estSocioEconomico.getUsuarioModifica(),
				//estSocioEconomico.getFechaModifica(),
				});
			if ( result.size() > 0 ) {
        		return (EstSocioEconomico) result.get(0);
        	} else {
        		return null;
        	}
    	}
    }

    // ------------- FindAllQuery ----------------------------------------    
    class FindAllQuery extends BaseQueryOperation {
		private static final String sql = "SELECT "
			+ "A.ID                AS ID, "
			+ "A.CODIGO            AS CODIGO, "
			+ "A.FECHA_INGRESO     AS FECHA_INGRESO, "
			+ "A.ID_SOLICITUD      AS ID_SOLICITUD, "
			+ "B.RADICADO          AS RADICADO, "
			+ "B.FECHA_RADICADO    AS FECHA_RADICADO, "
			+ "A.TIPO              AS TIPO, "
			+ "A.ESTADO            AS ESTADO, "
			+ "A.USUARIO_CREA      AS USUARIO_CREA, "
			+ "A.FECHA_CREA        AS FECHA_CREA, "
			+ "A.USUARIO_MODIFICA  AS USUARIO_MODIFICA, "
			+ "A.FECHA_MODIFICA    AS FECHA_MODIFICA "
			+ "FROM "
			+ "GES_EST_SOCIO_ECONOMICO_T A "
			+ "INNER JOIN "
			+ "ADM_SOLICITUD_T B "
			+ "ON "
			+ "A.ID_SOLICITUD = B.ID "
			+ "WHERE "
			+ "1=1 "
			+ "AND B.RADICADO = ? "
			+ "AND UPPER(A.CODIGO) LIKE ? "
			+ "AND UPPER(A.TIPO) LIKE ? "
			+ "AND UPPER(A.ESTADO) LIKE ? "		
			+ "ORDER BY A.ID ASC";
		
		public FindAllQuery(DataSource ds) {
    		super(ds,sql);
			declareParameter( new SqlParameter(Types.CHAR) );
			declareParameter( new SqlParameter(Types.CHAR) );
			declareParameter( new SqlParameter(Types.CHAR) );
			declareParameter( new SqlParameter(Types.CHAR) );
    		compile();
    	}
    	public List runQuery(EstSocioEconomicoComp estSocioEconomicoComp) {
			List result =  execute(new Object[]{
					estSocioEconomicoComp.getSolicitud().getRadicado(),
					new String("%" + (estSocioEconomicoComp.getCodigo()!=null&&!estSocioEconomicoComp.getCodigo().equals("")?estSocioEconomicoComp.getCodigo().toUpperCase():"%") + "%"),
					new String("%" + (estSocioEconomicoComp.getTipo()!=null&&!estSocioEconomicoComp.getTipo().equals("")?estSocioEconomicoComp.getTipo().toUpperCase():"%") + "%"),
					new String("%" + (estSocioEconomicoComp.getEstado()!=null&&!estSocioEconomicoComp.getEstado().equals("")?estSocioEconomicoComp.getEstado().toUpperCase():"%") + "%")
			});
			if ( result.size() > 0 ) {
        		return  result;
        	} else {
        		return null;
        	}
    	}
    }

    // ------------- FindByActiveStateQuery  -----------------------------
    class FindByActiveStateQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE;
    	public FindByActiveStateQuery(DataSource ds) {
    		super(ds,sql);
			compile();
    	}
    	public EstSocioEconomico runQuery(EstSocioEconomico estSocioEconomico) {
			List result =  execute( new Object[]{
			});
			if ( result.size() > 0 ) {
        		return (EstSocioEconomico) result.get(0);
        	} else {
        		return null;
        	}
    	}
    }

}
